<template>
    <div class="app-container">
      <div class="mapDiv">
        <!--地图-->
        <BuildingDamageEstimate
          :shpLegendList="shpLegendList"
          :shpDataList="fastSeismicInfluenceList"
          :geomList="geomList"
          :openInfluenceFieldButton="openInfluenceFieldButton"
          @seismicInfluenceSelect="seismicInfluenceSelect"
          @EstimateResult="EstimateResult"
        />
        <div v-show="showFastSeismicInfluenceDivBool" class="currentEventDiv">
          <!--快速生成地震影响场面板-->
          <el-form ref="addRef" label-width="100px" :model="form" :rules="rules">
            <el-row style="margin-bottom: 30px;">
              <el-col :span="24">
                <el-form-item label="建筑物数据" prop="buildingData" required>
                  <el-input v-model="form.buildingData" placeholder="请选择" readonly style="width:200px" />
                  <el-button @click="selectBuildingData">选择</el-button>
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
          <div style="text-align: center;margin-top: -20px;margin-bottom: 10px;">
            <el-button @click="createFastSeismicInfluence" type="primary">估计</el-button>
          </div>
        </div>
        <div v-show="showFastSeismicInfluenceDivBool" class="currentEventDiv1">
          <!--快速生成地震影响场面板-->
          <el-form ref="addRef" label-width="120px" :model="form" :rules="rules">
            <el-row style="margin-bottom: 30px;">
              <el-col :span="24">
                <el-form-item label="烈度级别选择">
                  <el-select v-model="dzIntensity" class="m-2" placeholder="请选择烈度" size="large" @change="changeDzIntensity" clearable>
                    <el-option
                      v-for="item in options"
                      :key="item.dzIntensity"
                      :label="item.intensity"
                      :value="item.dzIntensity"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
          <EcharsTable :titleName="titleName" :echartsListData="echartsListData" />
        </div>
        <!--快速生成地震影响场版本信息列表-->
        <el-dialog v-model="showFastSiVersionTableBool" title="快速影响场版本选择" width="900px" append-to-body @close="closeVersionSelectDialog">
          <div style="padding:10px;">
            <el-table v-loading="tableLoading" :data="fastSiVersionList" stripe>
              <el-table-column label="单选" width="55px">
                <template #default="scope">
                  <el-radio :label="scope.row.fvId" v-model="selectRadio"
                            @click.native.stop.prevent="getCurrentRow(scope.row)">&nbsp;</el-radio>
                </template>
              </el-table-column>
              <el-table-column label="地震影响场图编号" align="center" prop="versionCode" width="200" />
              <el-table-column label="长轴方向" align="center" prop="angle" width="100" />
              <el-table-column label="生成人" align="center" prop="createUserName" width="100" />
              <el-table-column label="生成时间" align="center" prop="createTime" width="100" />
              <el-table-column label="中心点经度" align="center" prop="longitude" width="100" />
              <el-table-column label="中心点纬度" align="center" prop="latitude" width="100" />
              <el-table-column label="震级" align="center" prop="earthquakeLevel" width="100" />
            </el-table>
            <pagination v-show="total > 0" :total="total" v-model:page="queryParams.page" v-model:limit="queryParams.rows"
                        @pagination="getFastSiVersionList" />
          </div>
          <template #footer>
            <div class="dialog-footer">
              <el-button type="primary" @click="submitVersionSelect">确 定</el-button>
            </div>
          </template>
        </el-dialog>
        <!--建筑物数据信息列表-->
        <el-dialog v-model="buildingDataTableBool" title="建筑物数据信息列表" width="900px" append-to-body @close="closeVersionSelectDialog1">
          <div style="padding:10px;">
            <el-table v-loading="tableLoading" :data="buildingDataList" stripe>
              <el-table-column label="单选" width="55px">
                <template #default="scope">
                  <el-radio :label="scope.row.id" v-model="selectRadio1"
                            @click.native.stop.prevent="getCurrentRow1(scope.row)">&nbsp;</el-radio>
                </template>
              </el-table-column>
              <el-table-column label="数据名称" align="center" prop="dataName" width="200" />
              <el-table-column label="版本号" align="center" prop="versionCode" width="100" />
              <el-table-column label="数据类型" align="center" prop="dataType" width="100" />
              <el-table-column label="版本范围" align="center" prop="dataRange" width="100" />
              <el-table-column label="版本说明" align="center" prop="versionDesc" width="100" />
              <el-table-column label="数据说明" align="center" prop="dataDesc" width="100" />
              <el-table-column label="版本日期" align="center" prop="versionTime" width="100" />
              <el-table-column label="上传人" align="center" prop="uploadUser" width="100" />
              <el-table-column label="上传日期" align="center" prop="uploadTime" width="100" />
            </el-table>
            <pagination v-show="total1 > 0" :total="total1" v-model:page="queryParams1.page" v-model:limit="queryParams1.rows"
                        @pagination="selectBuildingData" />
          </div>
          <template #footer>
            <div class="dialog-footer">
              <el-button type="primary" @click="selectBuildingDataButton">确 定</el-button>
            </div>
          </template>
        </el-dialog>
      </div>
    </div>
</template>
  
<script setup name="buildingDamageEstimate">
//地图
import BuildingDamageEstimate from '@/map/fastDisasterAnalysis/buildingDamageEstimate/indexMap.vue';
import EcharsTable from './echarsTable'
import { countEqIntensity, getFastSeismicInfluenceListByFvId, getFastSiVersionByFvId,
  getFastSiVersionListByXsemId,updateFastSiVersion,delFastSiVersion,countSurTaskManageByType,setSelectFastSiVersion,getFastSiVersionByXsemId } from "@/api/fastDisasterAnalysis/fastSeismicInfluence/intensity";
import { getDetail } from "@/api/comprehensiveInformation/seismicEvents.js"
import { getVersion,houseDestroyCountIntensityAndStructureOfArea,getModelData,houseDestroyEvaluate,getHouseDestoryResult,getHouseDestoryAreaSum} from "@/api/fastDisasterAnalysis/evaluationCalculation.js"
const { proxy } = getCurrentInstance();
import useEventStore from "@/store/modules/event";
import { ref } from 'vue';
const currentEvent = computed(() => useEventStore().currentEvent);
const router = useRouter();
const tableLoading = ref(false);
const data = reactive({
  form: {
    influenceVersion: '',
    buildingData: '',
  },
  queryParams: {
    page: 1,
    rows: 10,
  },
  queryParams1: {
    page: 1,
    rows: 10,
  },
  shpLegendList:[
    {fullName:"Ⅴ（5度）",name:"Ⅴ",value:"5",color:"rgba(255,220,220,0.7)",show:false},
    {fullName:"Ⅵ（6度）",name:"Ⅵ",value:"6",color:"rgba(255,190,190,0.7)",show:false},
    {fullName:"Ⅶ（7度）",name:"Ⅶ",value:"7",color:"rgba(255,127,127,0.7)",show:false},
    {fullName:"Ⅷ（8度）",name:"Ⅷ",value:"8",color:"rgba(200,40,40,0.7)",show:false},
    {fullName:"Ⅸ（9度）",name:"Ⅸ",value:"9",color:"rgba(168,0,0,0.7)",show:false},
    {fullName:"Ⅹ（10度）",name:"Ⅹ",value:"10",color:"rgba(140,0,0,0.7)",show:false},
    {fullName:"Ⅺ（11度）",name:"Ⅺ",value:"11",color:"rgba(105,0,0,0.7)",show:false},
    {fullName:"Ⅻ（12度）",name:"Ⅻ",value:"12",color:"rgba(80,0,0,0.7)",show:false},
  ],//灾区范围图例列表
  rules: {
      buildingData: [{ required: true, message: "建筑物数据不能为空", trigger: "blur" }],
  },
})
const { form,queryParams,shpLegendList,queryParams1,rules } = toRefs(data)
const options = ref([])
const dzIntensity = ref()
const echartsListData = ref({})
const titleName = ref('灾场房屋破坏结果统计')
//是否显示地震影响场版本信息列表表格
const showFastSiVersionTableBool = ref(false);
const showFsiSelectBool = ref(false);//是否显示选择快速影响场
const isInfluence = ref(false)
//选择地震影响场
const seismicInfluenceSelect = (val)=>{
  isInfluence.value = val
  showFsiSelectBool.value = val;
  if(val){
    showFastSiVersionTableBool.value = true;
    openInfluenceFieldButton.value = true
    // 根据事件ID查询地震影响场版本信息列表
    getFastSiVersionList();
  }else{
    showFastSiVersionTableBool.value = false;
    fastSeismicInfluenceList.value = [];
    openInfluenceFieldButton.value = false
  }
}
const selectRadio1 = ref('')
//地震影响场版本信息列表
const fastSiVersionList = ref([]);
const total = ref(0);//总数
// 根据事件ID查询地震影响场版本信息列表
function getFastSiVersionList(){
  let xsemId = currentEvent.value.id;
  if(xsemId){
    tableLoading.value = true;
    getFastSiVersionListByXsemId({xsemId,...queryParams.value}).then(res=>{
      fastSiVersionList.value = res.data.rows ? res.data.rows : [];
      total.value = res.data.total;
      tableLoading.value = false;
    })
  }
}
function createFastSeismicInfluence() {
  if(openInfluenceFieldButton.value) {
    getModelData({xsemId:currentEvent.value.id,}).then(resResult => {
      if(resResult.data != '' && resResult.data != null ) {
        proxy.$modal.confirm("重复评估会覆盖已有评估结果，请确认是否继续？",).then(function () {
          countResult()
        }).catch(() => {addnfluence() });
      }else{
        countResult()
      }
    })
  }else{
    proxy.$modal.msgWarning("请选取影响场版本");
  }
}
function countResult() {
  proxy.$modal.loading('正在计算，请稍等...')
  houseDestroyCountIntensityAndStructureOfArea({
    "xsemId":currentEvent.value.id,
    "buildingVersion":form.value.buildingData,
    "influenceVersion":form.value.influenceVersion,
    "fvId":selectRadio.value,
  }).then(res => {
      localStorage.setItem('buildingVersion', JSON.stringify(form.value.buildingData))
      houseDestroyEvaluate({
        "xsemId":currentEvent.value.id,
        "buildingVersion":form.value.buildingData,
        "influenceVersion":form.value.influenceVersion,
        "fvId":selectRadio.value,
      }).then(responseList => {
        getHouseDestoryResult({"xsemId":currentEvent.value.id,dzIntensity:''}).then(result => {
          options.value = result.data
          dzIntensity.value = result.data[0].dzIntensity
          echartsListData.value = result.data[0]
          titleName.value = '灾场房屋破坏结果统计'
          // geomList.value = result.data[0]
          showFastSeismicInfluenceDivBool.value = true
          proxy.$modal.closeLoading()
        }).catch(err => {
          proxy.$modal.closeLoading()
        })
      }).catch(err => {
          proxy.$modal.closeLoading()
        })
  }).catch(err => {
    proxy.$modal.closeLoading()
  })
}
const selectionData1 = ref([])
function getCurrentRow1(row) {
  if (selectRadio1.value) {
    if (selectRadio1.value == row.id) {
      selectRadio1.value = ''
      selectionData1.value = {};// 取消勾选就把回传数据清除
      return;
    }
  }
  selectRadio1.value = row.id;
  selectionData1.value = row;
}
const buildingDataTableBool = ref(false)
const buildingDataList = ref([])
const total1 = ref(0)
function selectBuildingData () {
  getVersion({dataType2: 115,...queryParams1.value}).then(res => {
    buildingDataTableBool.value = true
    buildingDataList.value = res.data.list
    total1.value = res.data.total
  }).catch()
}
const closeInfluence = ref(false)
//确定选择快速影响场版本
const submitVersionSelect = ()=>{
  if (selectRadio.value) {
    showFastSiVersionTableBool.value = false;
    closeInfluence.value = true
    // showFsiSelectBool.value = false;
    // 调查任务管理--根据类型查询事件的全部新建的评估子区数量
    countSurTaskManage();
  }else{
    fastSeismicInfluenceList.value = [];
    // showFsiSelectBool.value = false;
    proxy.$modal.msgWarning("请选取版本");
  }
}
function selectBuildingDataButton() {
  buildingDataTableBool.value = false
  if(selectionData1.value) {
    form.value.buildingData = selectionData1.value.versionCode
  }else{
    form.value.buildingData = ''
  }
}
//事件ID选择的地震影响场版本信息
const selectFastSiVersion = ref({});
// 调查任务管理--根据类型查询事件的全部新建的评估子区数量
function countSurTaskManage(){
  if(selectFastSiVersion.value && currentEvent.value){
    let fvId = selectFastSiVersion.value.fvId;
    let xsemId = currentEvent.value.id;
    // 调查任务管理--根据类型查询事件的全部新建的评估子区数量
    countSurTaskManageByType({xsemId: xsemId,type: "0"}).then(res=>{
      // 调查任务管理--事件的1个快速生成地震影响场版本信息设置选择
      setSelectFastSiVersionByFvId(xsemId);
    });
  }
}
const showFastSeismicInfluenceDivBool = ref(false)
const EstimateResult = (val) => {
    showFastSeismicInfluenceDivBool.value = val
}
// 调查任务管理--事件的1个快速生成地震影响场版本信息设置选择
function setSelectFastSiVersionByFvId(xsemId){
  let fvId = selectRadio.value;
  if(fvId){
    selectFastSiVersion.value = selectionData.value;
    // 调查任务管理--事件的1个快速生成地震影响场版本信息设置选择
    setSelectFastSiVersion(xsemId,fvId).then(res=>{
      console.log(res);
      // 根据版本ID查询地震影响场空间数据列表
      // getFastSeismicInfluenceList(fvId);
      initFunction();//初始化
    })
  }
}
//初始化
function initFunction(){
  let xsemId = currentEvent.value.id;
  if(xsemId){
    // 调查任务管理--根据事件ID查询选择的地震影响场版本信息
    getSelectFastSiVersionByXsemId(xsemId);
  }
}
// 调查任务管理--根据事件ID查询选择的地震影响场版本信息
function getSelectFastSiVersionByXsemId(xsemId){
  getFastSiVersionByXsemId(xsemId).then(res=>{
    let data = res.data;
    console.log(data);
    if(data){
      selectFastSiVersion.value = data;
      //确定选择
      // getCurrentRow(data);
       //根据事件ID查询灾区范围列表
      getSeismicInfluenceArray("");
    }
  })
}
//地震影响场空间数据列表
const fastSeismicInfluenceList = ref([]);
const liduJiBieData = ref([])
//类型zqfw,事件ID
const typeCode = ref("");
//根据事件ID查询灾区范围列表
function getSeismicInfluenceArray(geom){
  let fvId = selectFastSiVersion.value.fvId;
  if (fvId) {
    //
  }else{
    return;
  }
  if (currentEvent.value) {
    let xsemId = currentEvent.value.id;
    //类型zqfw,事件ID
    typeCode.value = "zqfw,"+xsemId;
    getFastSeismicInfluenceListByFvId(fvId,geom).then(response => {
      console.log("根据事件ID查询灾区范围列表");
      console.log(response.data);
      let list = response.data;
      if(geom){//新建|修改任务前查询空间范围是否在灾区范围内
        //新建任务
        openTask();
      }else{//初始化查询灾区范围
        fastSeismicInfluenceList.value = list;
        liduJiBieData.value = list
        if(list && list.length>0){
          let legendList = shpLegendList.value;
          for(let i=0;i<legendList.length;i++){
            let val = legendList[i].value;
            for(let j=0;j<list.length;j++){
              if(val==list[j].intensity){//烈度
                legendList[i].show = true;//只显示灾区范围的烈度
                break;
              }
            }
          }
          shpLegendList.value = legendList;
        }
      }
    });
  }else{
    fastSeismicInfluenceList.value = [];
  }
}
//选择快速影响场版本
const selectionData = ref({});
const selectRadio = ref('');
//单选选择
function getCurrentRow(row) {
  if (selectRadio.value) {
    if (selectRadio.value == row.fvId) {
      selectRadio.value = ''
      form.value.influenceVersion = ''
      selectionData.value = {};// 取消勾选就把回传数据清除
      return;
    }
  }
  form.value.influenceVersion = row.versionCode
  selectRadio.value = row.fvId;
  selectionData.value = row;
}
const closeVersionSelectDialog1 = () =>{
  buildingDataTableBool.value = false;
}
//关闭选择快速影响场版本
const closeVersionSelectDialog = () =>{
  showFastSiVersionTableBool.value = false;
  if(closeInfluence.value) {
    // openInfluenceFieldButton.value = true
  }else{
    openInfluenceFieldButton.value = false
  }
  closeInfluence.value = false
  // showFsiSelectBool.value = false;
}
function changeDzIntensity() {//灾场房屋破坏结果统计
  let data = options.value.find(item => dzIntensity.value == item.dzIntensity)
  if(data == undefined) {
    getHouseDestoryAreaSum({"xsemId":currentEvent.value.id}).then(result => {
      echartsListData.value = result.data
      titleName.value = '灾场房屋破坏结果统计'
    })
  }else{
    echartsListData.value = data
    titleName.value = '房屋破坏评估结果'
  }
  // geomList.value = data
}
const geomList = ref({})
const openInfluenceFieldButton = ref(false)
function addnfluence() {
  getModelData({xsemId:currentEvent.value.id,}).then(resResult => {
    if(resResult.data != '' && resResult.data != null ) {
      form.value.buildingData = resResult.data.buildingVersion == null?'':resResult.data.buildingVersion
      form.value.influenceVersion = resResult.data.influenceVersion == null?'':resResult.data.influenceVersion
    }
  })
}
onMounted(() => {
  setTimeout(() => {
    let xsemId = currentEvent.value.id
    getHouseDestoryAreaSum({"xsemId":currentEvent.value.id}).then(result => {
      if(result.data.length != 0) {
        getFastSeismicInfluenceListByFvId(result.data.fsiId,'').then(response => {
          console.log("根据事件ID查询灾区范围列表");
          console.log(response.data);
          let list = response.data;
          fastSeismicInfluenceList.value = list;
          liduJiBieData.value = list
          if(list && list.length>0){
            selectRadio.value = list[0].fvId
            let legendList = shpLegendList.value;
            openInfluenceFieldButton.value = true
            for(let i=0;i<legendList.length;i++){
              let val = legendList[i].value;
              for(let j=0;j<list.length;j++){
                if(val==list[j].intensity){//烈度
                  legendList[i].show = true;//只显示灾区范围的烈度
                  break;
                }
              }
            }
            shpLegendList.value = legendList;
          }
        });
        // options.value = [result.data]
        // dzIntensity.value = result.data[0].dzIntensity
        echartsListData.value = result.data
        titleName.value = '灾场房屋破坏结果统计'
        // geomList.value = result.data[0]
        showFastSeismicInfluenceDivBool.value = true
      }
    }).catch()
    getHouseDestoryResult({"xsemId":currentEvent.value.id,dzIntensity: ''}).then(result => {
      options.value = result.data
    })
    addnfluence()
  }, 500)
})
</script>
  
<style scoped lang="scss">
.mapDiv {
  position:absolute;top:0px;left:0px;width:100%;height:100%;
}
.currentEventDiv {
  position:absolute;top:20px;left:100px;background:rgba(255,255,255,0.8);border:1px solid gray;padding:20px;
}
.currentEventDiv1 {
  position:absolute;bottom:20px;right:20px;background:rgba(255,255,255,0.8);border:1px solid gray;padding:20px;
}
</style>
  
  